package com.express.base.dao;

import org.apache.ibatis.session.SqlSession;

import javax.annotation.Resource;
import java.lang.reflect.ParameterizedType;
import java.util.List;

/**
 * BaseDao的MyBatis实现
 * @author g
 *
 * @param <T>
 */
public class BaseDaoImpl<T> implements BaseDao<T> {

    @Resource(name = "sqlSessionTemplate")
    private SqlSession session;

    private final String path = "cn.express.mapper.";
    private Class type;

    public BaseDaoImpl() {
        this.type = this.getDAOClass();
    }

    @SuppressWarnings("all")
    private Class getDAOClass() {
        Class clazz = (Class) ((ParameterizedType) this.getClass().getGenericSuperclass())
                .getActualTypeArguments()[0];
        return clazz;
    }

    private String getMethodPath(String methodType) {
        return path + type.getSimpleName() + "Mapper." + methodType;
    }

    @Override
    public void save(T obj) {
        session.insert(getMethodPath("save"), obj);
    }

    @Override
    public void delete(T obj) {
        session.delete(getMethodPath("delete"), obj);
    }

    @Override
    public void update(T obj) {
        session.update(getMethodPath("update"), obj);
    }

    @Override
    public T get(Integer id) {
        return session.selectOne(getMethodPath("get"), id);
    }

    @Override
    public List<T> list() {
        return null;
    }
}
